package com.ikkong.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import sun.misc.BASE64Decoder;

import com.ikkong.common.util.CommonUtils;
import com.ikkong.core.constant.Cst;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.dao.Db;
import com.ikkong.core.toolbox.Func;
import com.ikkong.core.toolbox.Record;
import com.ikkong.core.toolbox.file.BladeFile;
import com.ikkong.core.toolbox.file.UploadFileUtils;
import com.ikkong.core.toolbox.kit.DateKit;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import com.ikkong.platform.model.Member;
import com.ikkong.platform.model.UserDocumentImage;
import com.ikkong.platform.model.UserInfo;
import com.ikkong.system.model.Attach;
import com.ikkong.api.intercept.CommonInterceptor;
import com.ikkong.api.intercept.TokenInterceptor;
import com.ikkong.api.model.BaseResponse;
import com.ikkong.api.model.Code;
import com.ikkong.api.model.DataResponse;
import com.ikkong.api.model.DatumResponse;
import com.ikkong.api.model.FileResponse;

/**
 * 文件上传总的控制器，所有文件上传类表单均拆分成文件上传和文本提交
 * 
 * @author mlongbo
 */

@Before({ CommonInterceptor.class, TokenInterceptor.class })
public class FileAPIController extends BaseAPIController {
	/**
	 * 修改头像接口 参数: 1.token 签名 2:imageData 图片数据（base64位）
	 * demo路径:http://blog.csdn.net/qq_36410795
	 * /article/details/72652027?locationNum=8&fps=1
	 */
	@Before(POST.class)
	@Clear(TokenInterceptor.class)
	public void PostImageData() {
		DatumResponse response = new DatumResponse();
		try {

			/*
			 * System.out.println(HttpKit.readData(getRequest())); String data =
			 * HttpKit.readData(getRequest()); System.out.println(data); String
			 * imageData =null; if(StringUtils.isEmpty(data)){ imageData
			 * =getPara("imageData"); }else{ JSONObject json =
			 * JSONObject.fromObject(data); imageData
			 * =json.getString("imageData"); }
			 * 
			 * System.out.println(imageData);
			 */

			String imageData = getPara("imageData");
			if (imageData.isEmpty()) {
				renderFailed("您没有上传头像");
				return;
			}
			// 输出base64 数据,截取","之后的值进行转换
			String str = imageData.substring(imageData.indexOf(",") + 1);

			/*
			 * String basePath = getRequest().getSession().getServletContext()
			 * .getRealPath("/");
			 */
			int AllowImgFileSize = 4194304; // 上传图片最大值(单位字节)（ 4 M = 4194304 B ）
			if (AllowImgFileSize != 0 && AllowImgFileSize < str.length()) {
				renderFailed("上传失败，请上传不大于4M的图片！");
				System.out.println("上传失败,base64图片大小:" + str.length() + "\n");
				return;
			}

			String basePath = (Cst.me().isRemoteMode() ? "" : PathKit
					.getWebRootPath());
			String filename = System.currentTimeMillis() + "";
			String avatar = basePath + "\\upload\\ocr\\headImg\\" + filename
					+ ".jpg";
			boolean flag = CommonUtils.GenerateImage(str, avatar);
			if (flag) {
				String url = "/upload/ocr/headImg/" + filename + ".jpg";
				response.setCode(Code.SUCCESS);
				response.setDatum(url);
				System.out.println("上传成功");
				renderJson(response);
				return;
			} else {
				renderFailed("上传失败");
				return;
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			renderError(e.getMessage());
		}
	}
	
	/**
	 * 提交识别图片
	 * 参数: 
	 * 1.token 签名 
	 * 2:imageData 图片数据（base64位）
	 * 3.template_id 所属模板
	 * 4.user_id  所属用户文档
	 */
	@Before(POST.class)
	public void postOcrImg() {
		DatumResponse response = new DatumResponse();
		try {
			Member member = getUser();
			int user_id = getParaToInt("user_id", 0);
			String imageData = getPara("imageData");
			int template_id = getParaToInt("template_id", 0);
			if (imageData.isEmpty()) {
				renderFailed("您没有上传头像");
				return;
			}
			// 输出base64 数据,截取","之后的值进行转换
			String str = imageData.substring(imageData.indexOf(",") + 1);

			/*
			 * String basePath = getRequest().getSession().getServletContext()
			 * .getRealPath("/");
			 */
			int AllowImgFileSize = 4194304; // 上传图片最大值(单位字节)（ 4 M = 4194304 B ）
			if (AllowImgFileSize != 0 && AllowImgFileSize < str.length()) {
				renderFailed("上传失败，请上传不大于4M的图片！");
				System.out.println("上传失败,base64图片大小:" + str.length() + "\n");
				return;
			}

			String basePath = (Cst.me().isRemoteMode() ? "" : PathKit
					.getWebRootPath());
			String filename = System.currentTimeMillis() + "";
			String avatar = basePath + "\\upload\\ocr\\img\\" + filename
					+ ".jpg";
			boolean flag = CommonUtils.GenerateImage(str, avatar);
		
			if (flag) {
				Date now=new Date();
				String dir = "/upload\\ocr\\img\\";
				String newfile_url = dir + filename + ".docx";
				//保存到数据库
				Blade userDocumentImageBlade = Blade.create(UserDocumentImage.class);
				UserDocumentImage userDocumentImage=userDocumentImageBlade.findFirstBy("user_id=#{user_id}&&template_id=#{template_id}", 
						Record.create().set("user_id", user_id).set("template_id", template_id));
				if(userDocumentImage!=null){
					//先删除图片
					String url=	userDocumentImage.getPath();
					if(!StringUtils.isEmpty(url)){
						String path = (Cst.me().isRemoteMode() ? "" : PathKit.getWebRootPath()) + url;
						File f = new File(path);
						if (!f.exists()) {
							f.delete();
						}
					}
					userDocumentImage.setPath(newfile_url);
					userDocumentImage.setModifyTime(now);
					userDocumentImage.setMark(null);
					userDocumentImage.setStatus(1);
					userDocumentImageBlade.update(userDocumentImage);

				}else{
					//新增图片
					UserDocumentImage newUserDocumentImage=new UserDocumentImage();
					newUserDocumentImage.setCreateTime(now);
					newUserDocumentImage.setMember_id(member.getId());
					newUserDocumentImage.setModifyTime(now);
					newUserDocumentImage.setPath(newfile_url);
					newUserDocumentImage.setStatus(1);
					newUserDocumentImage.setTemplate_id(template_id);
					newUserDocumentImage.setUser_id(user_id);
					userDocumentImageBlade.save(newUserDocumentImage);
				}
				
				
				
				response.setCode(Code.SUCCESS);
				response.setDatum(newfile_url);
				System.out.println("上传成功");
				renderJson(response);
				return;
			} else {
				renderFailed("上传失败");
				return;
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			renderError(e.getMessage());
		}
	}
	

	/**
	 * 修改头像接口 参数: 1.token 签名 2:imageData 图片数据（base64位）
	 * demo路径:http://blog.csdn.net/qq_36410795
	 * /article/details/72652027?locationNum=8&fps=1
	 */
	/*
	 * @Before(POST.class) public void uploadfile() { DatumResponse response =
	 * new DatumResponse(); try { String currentTime=DateKit.getDays();
	 * System.out.println(currentTime); Member member = getUser(); int userId =
	 * member.getId(); String imageData = getPara("imageData");
	 * System.out.println(imageData); if (imageData.isEmpty()) {
	 * renderArgumentError("您没有上传头像"); return; } // 输出base64 数据,截取","之后的值进行转换
	 * String str = imageData.substring(imageData.indexOf(",") + 1); String
	 * basePath = getRequest().getSession().getServletContext()
	 * .getRealPath("/"); String filename = System.currentTimeMillis() + "";
	 * String avatar = basePath + "\\upload\\ocr\\" + filename+ ".jpg"; boolean
	 * flag = CommonUtils.GenerateImage(str, avatar); if (flag) { Blade blade =
	 * Blade.create(Attach.class); Attach attach = new Attach();
	 * attach.setCreater(userId); attach.setCreatetime(new Date());
	 * attach.setName(filename); attach.setStatus(1);
	 * attach.setUrl("/upload\\"+currentTime+"\\" + filename + ".jpg");
	 * System.out.println("/upload\\"+currentTime+"\\" + filename + ".jpg");
	 * boolean f = blade.save(attach); if (f) { String url = "/upload/"+
	 * currentTime+"/" + filename + ".jpg";
	 * 
	 * response.setCode(Code.SUCCESS); response.setDatum(url);
	 * renderJson(response); } else { renderFailed("上传失败"); } } else {
	 * renderFailed("上传失败"); } } catch (Exception e) {
	 * System.out.println(e.getMessage()); renderError(e.getMessage()); } }
	 */

	/*
	 * 上传文件 (单个) dir:上传文件类型（image,flash,media,file,allfile）
	 */
	@Before(POST.class)
	// @Clear(TokenInterceptor.class)
	public void upload() {
		FileResponse response = new FileResponse();
		try {
			Member member = getUser();
			if (member.getBank_id() == 0) {
			}
			// UploadFile file = getFile(getPara("imgFile"));
			UploadFile file = getFile();
			Record maps = Record.create();
			if (null == file) {
				response.setCode(Code.FAIL);// 表示此次上传有未上传成功的文件
				response.setMessage("请选择要上传的图片");
				renderJson(response);
				return;
			}
			String originalFileName = file.getOriginalFileName();
			System.out.println(originalFileName);
			/*
			 * extMap.put("image", ".gif,.jpg,.jpeg,.png,.bmp");
			 * extMap.put("flash", ".swf,.flv"); extMap.put("media",
			 * ".swf,.flv,.mp3,.mp4,.wav,.wma,.wmv,.mid,.avi,.mpg,.asf,.rm,.rmvb"
			 * ); extMap.put("file",
			 * ".doc,.docx,.xls,.xlsx,.ppt,.htm,.html,.txt,.zip,.rar,.gz,.bz2");
			 * extMap.put( "allfile",
			 * ".gif,.jpg,.jpeg,.png,.bmp,.swf,.flv,.mp3,.mp4,.wav,.wma,.wmv,.mid,.avi,.mpg,.asf,.rm,.rmvb,.doc,.docx,.xls,.xlsx,.ppt,.htm,.html,.txt,.zip,.rar,.gz,.bz2"
			 * );
			 */
			String dir = getPara("dir", "image");
			// 测试后缀
			boolean ok = UploadFileUtils.testExt(dir, originalFileName);
			if (!ok) {
				response.setCode(Code.FAIL);// 表示此次上传有未上传成功的文件
				response.setMessage("上传文件的类型不允许");
				renderJson(response);
				return;
			}

			UploadFileUtils.transfer(file);
			BladeFile bf = new BladeFile(file);
			bf.transfer();
			Object fileId = bf.getFileId();
			String path = bf.getUploadVirtualPath();
			// String url = "/api/file/renderFile/" + fileId;

			maps.set("fileId", fileId);
			// maps.set("url", Cst.me().getContextPath() + url);
			maps.set("url", path);
			maps.set("fileName", originalFileName);
			// maps.set("path", Cst.me().getContextPath() +
			// bf.getUploadVirtualPath());
			response.setCode(Code.SUCCESS);// 表示此次上传有未上传成功的文件
			response.setDatum(maps);
			renderJson(response);
		} catch (Exception e) {
			response.setCode(Code.ERROR);// 表示此次上传有未上传成功的文件
			renderJson(response);
		}
	}

	/*
	 * 上传文件(多个) dir:上传文件类型（image,flash,media,file,allfile）
	 */
	@Before(POST.class)
	// @Clear(TokenInterceptor.class)
	public void uploadMulit() {
		FileResponse response = new FileResponse();
		try {

			// UploadFile file = getFile(getPara("imgFile"));
			List<UploadFile> fileList = getFiles();
			List<Record> maps = new ArrayList<Record>();
			if (null == fileList) {

				response.setCode(Code.FAIL);// 表示此次上传有未上传成功的文件
				response.setMessage("请选择要上传的图片");
				renderJson(response);
				return;
			}
			for (UploadFile file : fileList) {
				Record map = Record.create();
				// File file = uploadFile.getFile();
				String originalFileName = file.getOriginalFileName();

				String dir = getPara("dir", "image");
				// 测试后缀
				boolean ok = UploadFileUtils.testExt(dir, originalFileName);
				if (!ok) {
					response.setCode(Code.FAIL);// 表示此次上传有未上传成功的文件
					response.setMessage("上传文件的类型不允许");
					renderJson(response);
					return;
				}

				UploadFileUtils.transfer(file);
				BladeFile bf = new BladeFile(file);
				bf.transfer();
				Object fileId = bf.getFileId();
				String url = "/api/file/renderFile/" + fileId;

				map.set("fileId", fileId);
				map.set("url", Cst.me().getContextPath() + url);
				map.set("fileName", originalFileName);
				// map.set("path", Cst.me().getContextPath() +
				// bf.getUploadVirtualPath());
				maps.add(map);
			}
			response.setCode(Code.SUCCESS);// 表示此次上传有未上传成功的文件
			response.setDatum(maps);
			renderJson(response);
		} catch (Exception e) {
			response.setCode(Code.ERROR);// 表示此次上传有未上传成功的文件
			renderJson(response);
		}
	}

	@Before(GET.class)
	@Clear(TokenInterceptor.class)
	public void renderFile() {
		String id = getPara(0);
		Map<String, Object> file = Db.init().findById("TFW_ATTACH", id);
		if (Func.isEmpty(file)) {
			redirect("/error/error404");
			return;
		} else {
			String url = file.get("URL").toString();
			File f = new File((Cst.me().isRemoteMode() ? ""
					: PathKit.getWebRootPath())
					+ url);
			renderFile(f);
		}
	}

	/*	*//**
	 * 处理单文件或多文件上传，上传成功后，返回url集合
	 */
	/*
	 * @Before(POST.class)
	 * 
	 * @Clear(TokenInterceptor.class) public void uploadfile() {
	 * 
	 * FileResponse response = new FileResponse(); try { List<UploadFile>
	 * fileList = getFiles();// 已接收到的文件 if (fileList != null &&
	 * !fileList.isEmpty()) { Map<String, String> urls = new HashMap<String,
	 * String>();// 用于保存上传成功的文件地址 List<String> failedFiles = new
	 * ArrayList<String>(); // 用于保存未成功上传的文件名
	 * 
	 * for (UploadFile uploadFile : fileList) { File file =
	 * uploadFile.getFile(); String urlPath = FileUtils.saveUploadFile(file); if
	 * (StringUtils.isEmpty(urlPath)) {
	 * failedFiles.add(uploadFile.getParameterName()); // 标记为上传失败 } else {
	 * //返回相对路径,用于响应 urls.put(uploadFile.getParameterName(), urlPath +
	 * file.getName()); } } response.setDatum(urls); if (failedFiles.size() > 0)
	 * { response.setCode(Code.FAIL);// 表示此次上传有未上传成功的文件
	 * response.setFailed(failedFiles);
	 * 
	 * } } else { response.setCode(Code.ARGUMENT_ERROR).setMessage(
	 * "uploadFileName can not be null"); } } catch (Exception e) {
	 * e.printStackTrace(); response.setCode(Code.ERROR); }
	 * renderJson(response);
	 * 
	 * }
	 */

}